package com.audaque.springboot.foshanupload.web.websocketdemo.encoder;

import com.audaque.springboot.foshanupload.web.websocketdemo.model.req.MessageReq;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;

import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;

public class JsonEncoder implements Encoder.Text<MessageReq> {
    @Autowired
    private ObjectMapper objectMapper;
    @Override//Initialization does nothing
    public void init(EndpointConfig config) {
    }

    @Override//Encoding process(Object → JSON)
    public String encode(MessageReq obj) throws EncodeException {

        String json = "";
        try {
            json = objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return json;
    }

    @Override//Do nothing to destroy
    public void destroy() {
    }
}
